<template>
  <div>
    <a-card class="table-card">
      <div>
        <a-row style="font-weight: bold; margin: 0 30px; line-height: 60px;">
          <a-col :span="6">活动编号：{{ vdata.activityDetail['activityNo'] }}</a-col>
          <a-col :span="6">活动名称：{{ vdata.activityDetail['activityName'] }}</a-col>
          <a-col :span="6">活动时间：{{ vdata.activityDetail['startTime'] }} 到 {{ vdata.activityDetail['endTime'] }}</a-col>
          <a-col :span="6" style="text-align: right;">
            <!-- <a-button :loading="vdata.exportLoading" type="link" @click="onExport">
              <export-outlined />
              一键导出
            </a-button> -->
          </a-col>
        </a-row>
        <a-divider style="margin: 0" />
      </div>

      <a-divider style="margin: 0px;" />

      <template v-for="(item, index) in vdata.activityAwardList">
        <a-row style="font-weight: bold; margin: 0 30px; line-height: 60px;">
          <a-col :span="6">奖品编号：{{ item.awardId }}</a-col>
          <a-col :span="6">奖品类型：{{ item.awardType === 0 ? '卡券' : item.awardType === 1 ? '实物' : item.awardType === 2 ? '虚拟券' : '积分' }}</a-col>
          <a-col :span="6">奖品名称：{{ item.awardName }}</a-col>
        </a-row>
        <GzSearchForm :searchFunc="item.searchFunc" :resetFunc="item.resetFunc" searchConditionNum="6">
          <a-form-item class="table-search-item" label="领用人手机号">
            <a-input v-model:value="item.searchData['phone']" :placeholder="'领用人手机号'" />
          </a-form-item>
          <a-form-item class="table-search-item" label="领用开始时间">
            <a-date-picker v-model:value="item.searchData['startTime']" :placeholder="'领用开始时间'" style="width: 100%;" />
          </a-form-item>
          <a-form-item class="table-search-item" label="领用结束时间">
            <a-date-picker v-model:value="item.searchData['endTime']" :placeholder="'领用结束时间'" style="width: 100%;" />
          </a-form-item>
          <a-form-item class="table-search-item" label="客户ID">
            <a-input v-model:value="item.searchData['customerId']" :placeholder="'客户ID'" />
          </a-form-item>
          <template #footer>
            <a-button type="primary" :loading="item.btnLoading" class="ref-left-10" @click="exportSingleAwardDataHandler(item)">
              <export-outlined />导出
            </a-button>
          </template>
        </GzSearchForm>

        <!-- 列表渲染 -->
        <GzTable
          v-if="vdata.activityAwardList.length"
          :ref="'infoTableRef' + index"
          :init-data="true"
          :req-table-data-func="reqTableDataFunc"
          :table-columns="item.tableColumns"
          :search-data="item.searchData"
        >
          <template #topBtnSlot />
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'operation'" />
          </template>
        </GzTable>
        <a-divider style="margin: 0" />
      </template>

      <a-affix :offset-bottom="20">
        <div style="background-color: white;">
          <a-divider style="margin: 0; margin-top: 20px;" />
          <div class="bottom-buttons">
            <div class="bottom-buttons-item" @click="emits('switchApplyPage', { page: 'list' })">
              <a-button type="link" style="color: #808080 ;"><left-outlined />返回列表页</a-button>
            </div>
            <div class="bottom-buttons-item" />
          </div>
        </div>
      </a-affix>
    </a-card>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, getCurrentInstance, defineExpose, computed } from 'vue'
import { API_URL_EXPORT_ACTIVITY_AWARD, $exportExcel } from '@/api/manage'
import { $getActivityAwardList, $getActivityAwardDetail, $exportSingleAwardData, $exportAllAwardData } from '@/api/activityManage/activityList/index'
// 获取当前实例
const { proxy }: any = getCurrentInstance()
const { $access, $infoBox } = getCurrentInstance()!.appContext.config.globalProperties

const emits = defineEmits(['switchApplyPage'])

// 搜索条件
const searchData = ref({})

// 数据源
const vdata : any = reactive({
  activityDetail: {}, // 活动详情
  activityAwardList: [],  // 活动奖品列表 需要根据奖品列表循环table表格（用户领用信息表），其中包含每个表格的搜索条件、搜索函数、重置函数、表头
  activityFansAwardList: [],  // 用户领奖列表

  exportLoading: false, // 导出按钮loading
})

// 卡券表头
const couponTableColumns = reactive([
  { title: '用户唯一ID', key: 'fansId', dataIndex: 'fansId', fixed: 'left', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '参与客户姓名', key:'realName', dataIndex:'realName', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '参与客户手机号', key: 'phone', dataIndex: 'phone', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '参与客户是否实名', key: 'isAuth', dataIndex: 'isAuth', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '领用卡券名称', key: 'couponName', dataIndex: 'couponName', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '卡券金额', key: 'couponPrice', dataIndex: 'couponPrice', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '微信唯一卡券编号', key: 'couponThirdId', dataIndex: 'couponThirdId', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '参与时间', key: 'createdAt', dataIndex: 'createdAt', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '核销时间', key: 'writeTime', dataIndex: 'writeTime', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '卡券状态', key:'status', dataIndex:'status', width: 150, minWidth: 150, maxWidth: 180 },
])
// 实物表头
const goodsTableColumns = reactive([
  { title: '用户唯一ID', key: 'fansId', dataIndex: 'fansId', fixed: 'left', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '参与客户姓名', key:'realName', dataIndex:'realName', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '参与客户手机号', key: 'phone', dataIndex: 'phone', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '参与客户是否实名', key: 'isAuth', dataIndex: 'isAuth', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '领用奖品名称', key: 'goodsName', dataIndex: 'goodsName', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '参与时间', key: 'createdAt', dataIndex: 'createdAt', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '核销时间', key: 'writeTime', dataIndex: 'writeTime', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '实物状态', key:'status', dataIndex:'status', width: 150, minWidth: 150, maxWidth: 180 },
])
// 虚拟券表头
const virtualTableColumns = reactive([
  { title: '用户唯一ID', key: 'fansId', dataIndex: 'fansId', fixed: 'left', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '参与客户姓名', key:'realName', dataIndex:'realName', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '参与客户手机号', key: 'phone', dataIndex: 'phone', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '参与客户是否实名', key: 'isAuth', dataIndex: 'isAuth', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '领用奖品名称', key: 'goodsName', dataIndex: 'goodsName', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '参与时间', key: 'createdAt', dataIndex: 'createdAt', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '核销时间', key: 'writeTime', dataIndex: 'writeTime', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '实物状态', key:'status', dataIndex:'status', width: 150, minWidth: 150, maxWidth: 180 },
])
// 福分表头
const scoreTableColumns = reactive([
  { title: '用户唯一ID', key: 'fansId', dataIndex: 'fansId', fixed: 'left', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '参与客户姓名', key:'realName', dataIndex:'realName', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '参与客户手机号', key: 'phone', dataIndex: 'phone', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '参与客户是否实名', key: 'isAuth', dataIndex: 'isAuth', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '领用福分名称', key: 'name', dataIndex: 'name', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '领用福分值', key: 'score', dataIndex: 'score', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '参与时间', key: 'createdAt', dataIndex: 'createdAt', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '核销时间', key: 'writeTime', dataIndex: 'writeTime', width: 150, minWidth: 150, maxWidth: 180 },
  { title: '卡券状态', key:'status', dataIndex:'status', width: 150, minWidth: 150, maxWidth: 180 },
])

// 列表请求接口
function reqTableDataFunc(params) {
  return $getActivityAwardDetail({ ...params, activityId: vdata.activityDetail.activityId })
}

// 单奖品数据导出
async function exportSingleAwardDataHandler(item) {
  try {
    item.btnLoading = true
    await $exportSingleAwardData({ ...item.searchData, awardName: item.awardName })
    $infoBox.message.success('导出成功，请到下载目录查看')
  } catch (error) {
  } finally {
    item.btnLoading = false
  }
}

// 搜索函数
function searchFuncHandler(index) {
  proxy.$refs[`infoTableRef${index}`][0].refTable(true)
}
// 重置函数
function resetFuncHandler(index) {
  const { awardId, awardType } = vdata.activityAwardList[index].searchData
  // 重置awardId和awardType以外的条件
  vdata.activityAwardList[index].searchData = { awardId, awardType }
}
/**
 * 导出
 */
async function onExport() {
  try {
    vdata.exportLoading = true
    await $exportAllAwardData({ activityId: vdata.activityDetail.activityId })
    $infoBox.message.success('导出成功，请到下载目录查看')
  } catch (error) {
  } finally {
    vdata.exportLoading = false
  }
}

// 请求活动奖品信息
async function getActivityAwardList(activityId) {
  const awardList = await $getActivityAwardList(activityId)
  vdata.activityAwardList = awardList.map((item,index) => {
    return {
      ...item,
      btnLoading: false,
      searchData: {
        awardId: item.awardId,
        awardType: item.awardType
      },
      searchFunc: () => {
        searchFuncHandler(index)
      },
      resetFunc: () => {
        resetFuncHandler(index)
      },
      tableColumns: tableColumnsHandler(item)
    }
  })
}

// 根据奖品类型返回对应表头
function tableColumnsByType(awardType) {
  // 动态表头 根据不同奖品类型展示不同表头 计算属性 awardType 0卡券1实物2虚拟3积分
  switch (awardType) {
    case 0:
      return couponTableColumns
    case 1:
      return goodsTableColumns
    case 2:
      return virtualTableColumns
    case 3:
      return scoreTableColumns
    default:
      return []
  }
}

// 处理表头 表头需要根据是否入链和是否激活以及奖品类型动态调整
function tableColumnsHandler(award) {
  const { awardType, thumbMediaId, isNeedActivate } = award
  const baseColumns = JSON.parse(JSON.stringify(tableColumnsByType(awardType)))  // 克隆一份表头
  if (thumbMediaId){  // 包含入链表头
    baseColumns.push(
      { title: '入链渠道', key:'channelType', dataIndex:'channelType', width: 150, minWidth: 150, maxWidth: 180 },
      { title: '入链账号', key:'channelCode', dataIndex:'channelCode', width: 150, minWidth: 150, maxWidth: 180 },
      { title: '入链账号名称', key:'channelName', dataIndex:'channelName', width: 150, minWidth: 150, maxWidth: 180 },
      { title: '入链账号所属网点机构号', key:'channelAgentNo', dataIndex:'channelAgentNo', width: 200, minWidth: 200, maxWidth: 250 },
    )
  }
  if (isNeedActivate){  // 包含激活相关表头
    baseColumns.push(
      { title: '激活客户经理归属机构号', key:'agentNo', dataIndex:'agentNo', width: 200, minWidth: 200, maxWidth: 250 },
      { title: '激活客户经理归属网点', key:'agentName', dataIndex:'agentName', width: 200, minWidth: 200, maxWidth: 250 },
      { title: '激活客户经理姓名', key:'employeeName', dataIndex:'employeeName', width: 200, minWidth: 200, maxWidth: 250 },
      { title: '激活客户经理手机号', key:'employeePhone', dataIndex:'employeePhone', width: 200, minWidth: 200, maxWidth: 250 },
    )
  }
  return baseColumns
}


// 页面渲染函数
async function pageRender({ activityDetail }) {
  vdata.activityDetail = activityDetail
  const { activityId } = activityDetail
  // 请求活动对应奖品列表
  await getActivityAwardList(activityId)
  // 请求每个奖品对应的领奖列表
  // const activityFansAwardList = await Promise.all(vdata.activityAwardList.map(item => $getActivityAwardDetail(item.awardId, item.awardType)))
  // vdata.activityFansAwardList = activityFansAwardList
}

defineExpose({
  pageRender
})

</script>

<style lang="less" scoped>

.bottom-buttons{
  display: flex; flex-direction: row; justify-content: center; height: 60px;

  .bottom-buttons-item{
    flex-grow: 1; display: flex; flex-direction: column; justify-content: center;
  }

   .bottom-buttons-item:hover{
    transition: 0.3s ease;
    background-color: rgba(23, 91, 230, 0.05);
    cursor: pointer;
  }

}
</style>